<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  
</head>
<style>
   #box {
    padding: 20px;
    background: palegoldenrod;
  }
</style>
<body>
  <div id="box"></div>
  <button id="btn1">执行计算任务</button>
  <button id="btn2">更改背景颜色</button>
</body>
<script>
    const box = document.getElementById('box')
  const btn1 = document.getElementById('btn1')
  const btn2 = document.getElementById('btn2')

  let number = 999999
  let value = 0
  let shd=undefined

  function calc(deadline) {
    while (number > 0 && deadline.timeRemaining() > 0) {
      value = Math.random() < 0.5 ? Math.random() : Math.random()
      // console.log(value)
      number--
    }
     shd=requestIdleCallback(calc)
  }

  btn1.onclick = function () {
    //requestIdlecallback(参考https://www.cnblogs.com/goloving/p/14074006.html，
    // https://blog.csdn.net/qq_36380426/article/details/107602810/，
    // https://www.bilibili.com/video/BV19W4y1W7yx/?spm_id_from=333.337.search-card.all.click&vd_source=009ec7b09b6a18588257bad29cd0d0cc，
    // 的用法)
    shd=requestIdleCallback(calc)
  }

  btn2.onclick = function () {
    box.style.background = 'green'
     cancelIdleCallback(shd)
  }
  //在vue中卸载组件要停止requestIdleCallback(calc)中的calc函数
  // onunmounted(()=>{
  //   cancelIdleCallback(shd)
  // })
    
</script>
</html>
